import {
  getSongPlay
} from "../../../utils/http"
const audio = getApp().audio
Page({
  pageNumber: 1, // 起始页
  prevSongId: null, // 上一次播放的歌曲id
  nowSongId: null, // 本次播放的歌曲id
  data: {
    playWay: true, // 播放方式。单曲:false , 全部:true
  },
  onLoad() {
    let songList = wx.getStorageSync('collectionMusic') || []
    songList.map(item => delete item.status && delete item.songData) // 收藏时已经去除，避免其他过程中重复赋值，故再次删除
    this.setData({
      songList
    })
  },
  // 取消收藏
  async calcelCollection(e) {
    let {
      id
    } = e.currentTarget.dataset
    let songList = this.data.songList.filter(item => item.songId != id)
    this.setData({
      songList
    })
    wx.setStorage({
      key: "collectionMusic",
      data: songList,
      success: () => {
        wx.showToast({
          title: '已取消收藏',
          icon: 'none'
        })
      }
    })
  },
  // 开始监听（在开始播放之后执行）
  startOnPlay() {
    // 监听背景音频播放事件
    audio.onPlay(() => {
      console.log("播放")
      let index = this.data.songList.findIndex(item => item.songId == this.nowSongId)
      if (index > -1) {
        this.setData({
          [`songList[${index}].status`]: "playing",
          isPlaying: true,
          nowSongIndex: index
        })
      }
    })
    // 监听用户在系统音乐播放面板点击上一曲事件的监听函数
    audio.onPrev(() => {
      console.log("上一首")
      this.playPrevAudio()
    })
    // 监听用户在系统音乐播放面板点击下一曲事件
    audio.onNext(() => {
      console.log("下一首")
      this.playNextAudio()
    })
    // 监听背景音频自然播放结束事件
    audio.onEnded(() => {
      console.log("自然结束")
      let index = this.data.songList.findIndex(item => item.songId == this.nowSongId)
      if (index > -1) {
        this.setData({
          [`songList[${index}].status`]: "stop",
          isPlaying: false,
          nowSongIndex: index
        })
        if (this.data.playWay) {
          this.playNextAudio()
        } else(
          this.startPlayAudio()
        )
      }
    })
    // 监听背景音频暂停事件
    audio.onPause(() => {
      console.log("暂停")
      let index = this.data.songList.findIndex(item => item.songId == this.nowSongId)
      if (index > -1) {
        this.setData({
          [`songList[${index}].status`]: "pauseing",
          isPlaying: false,
          nowSongIndex: index
        })
      }
    })
    // 监听背景音频停止事件
    audio.onStop(() => {
      console.log("停止")
      let index = this.data.songList.findIndex(item => item.songId == this.prevSongId)
      let index2 = this.data.songList.findIndex(item => item.songId == this.nowSongId)
      if (index > -1) {
        this.setData({
          [`songList[${index}].status`]: "stop",
          isPlaying: false,
          nowSongIndex: index2
        })
      }
    })
    audio.onError(() => {
      console.log("错误")
      let index = this.data.songList.findIndex(item => item.songId == this.nowSongId)
      if (index > -1) {
        this.setData({
          [`songList[${index}].status`]: "stop",
          [`songList[${index}].songData`]: null,
          isPlaying: false,
          nowSongIndex: index
        })
      }
      this.playNextAudio()
      // this.startPlayAudio()
    })
  },
  // 点击播放按钮
  playAudio(e) {
    if (!this.nowSongId) {
      this.startOnPlay()
    }
    this.nowSongId = e.currentTarget.dataset.id
    this.startPlayAudio()
  },
  // 暂停
  pauseAudio() {
    audio.pause()
  },
  // 上一首
  playPrevAudio() {
    let index = this.data.songList.findIndex(item => item.songId == this.nowSongId)
    if (index <= 0) {
      this.nowSongId = this.data.songList[this.data.songList.length - 1].songId
    } else {
      this.nowSongId = this.data.songList[index - 1].songId
    }
    this.startPlayAudio()
  },
  // 下一首
  playNextAudio() {
    let index = this.data.songList.findIndex(item => item.songId == this.nowSongId)
    if (index < this.data.songList.length - 1) {
      this.nowSongId = this.data.songList[index + 1].songId
    } else {
      this.nowSongId = this.data.songList[0].songId
    }
    this.startPlayAudio()
  },
  // 切换播放方式
  changePlayWay() {
    this.setData({
      playWay: !this.data.playWay
    })
  },
  // 加载SongList歌曲数据并播放
  async getSongListData(songId) {
    wx.showLoading({
      title: '',
      mask: true
    })
    let res = await getSongPlay({
      songId
    })
    wx.hideLoading()
    if (res.code !== 200) {
      setTimeout(() => {
        this.playNextAudio()
      }, 2000)
      return wx.showToast({
        title: res.msg + "。即将尝试播放下一曲",
        icon: 'none',
        duration: 2000
      })
    }
    if (!res.data.url) { // 谨防歌曲链接不存在的情况，则播放下一首
      setTimeout(() => {
        this.playNextAudio()
      }, 2000)
      return wx.showToast({
        title: "歌曲链接丢失，即将尝试播放下一曲",
        icon: 'none',
        duration: 2000
      })
    }
    let index = this.data.songList.findIndex(item => item.songId == this.nowSongId)
    let item = this.data.songList[index]
    audio.stop()
    audio.src = res.data.url
    audio.title = item.title
    audio.singer = item.singer
    audio.coverImgUrl = res.data.pic
    audio.play()
    this.setData({
      [`songList[${index}].songData`]: res.data
    })
  },
  // 播放指定歌曲
  async startPlayAudio() {
    let item = this.data.songList.filter(item => item.songId == this.nowSongId)[0]
    let {
      songId,
    } = item
    // 两次播放的是同一首歌
    if (this.prevSongId == this.nowSongId) {
      console.log("前后是同一首歌")
      // 当前状态stop且有歌词
      if (item.status && item.status == "stop" && item.songData) {
        console.log("当前状态stop且有歌词")
        audio.src = item.songData.url
        audio.title = item.title
        audio.singer = item.singer
        audio.coverImgUrl = item.songData.pic
        audio.play()
      }
      // 当前状态pauseing，继续播放
      else if (item.status && item.status == "pauseing") {
        console.log("当前状态pauseing，继续播放")
        audio.play()
      }
      // 当前没有状态，有歌词就播放
      else if (item.songData) {
        console.log("当前没有状态，有歌词就播放")
        audio.stop()
        audio.src = item.songData.url
        audio.title = item.title
        audio.singer = item.singer
        audio.coverImgUrl = item.songData.pic
        audio.play()
      } else {
        // 一穷二白，获取数据
        console.log("一穷二白，获取数据")
        await this.getSongListData(songId)
      }
    } else { // 前后不是同一首歌，先停止前一首播放
      if (item.songData) {
        audio.stop()
        console.log("前后不是同一首歌，但有歌词")
        audio.src = item.songData.url
        audio.title = item.title
        audio.singer = item.singer
        audio.coverImgUrl = item.songData.pic
        audio.play()
      } else {
        console.log("前后不是同一首歌，且无歌词")
        await this.getSongListData(songId)
      }
    }
    // 重置上次播放index为本次的，之所以用定时，是因为音频组件在监听，它会慢一点
    setTimeout(() => {
      this.prevSongId = this.nowSongId
    }, 100)
  },
})